import logging
import os
import sys
import subprocess
#import argparse
import tempfile


from exome.gatk_cluster.reads.realignment_job import fast_lane_level_processing
import exome.snps_callers.snps_byGatk as sgatk
import exome.snps_callers.snps_bySamTools2 as sst



from collections import defaultdict, deque
from optparse import OptionParser

from exome.jobs.base import JOB_SUCCESS, JOB_ERROR
from exome.jobs.job_runner import qsub_cac, qsub_loc, run_local
from exome.jobs.config import ExomePipelineConfig, ExomeAnalysisConfig

if __name__ == '__main__':
        
    optionparser = OptionParser("usage: %prog [options] ")
    optionparser.add_option("-r", "--config_file", dest="config_file",
                            help="file with run configuration")
    optionparser.add_option("-a", "--analysis_file", dest="analysis_file",
                            help="file with experiment configuration")  
    optionparser.add_option("--local", dest="local", action="store_true", default=False)
    optionparser.add_option("--cluster", dest="cluster", action="store_true", default=False)
    optionparser.add_option("-p", "--processes", type=int, dest="num_processors", default=1)
    optionparser.add_option("--paired_samples", dest="paired_samples", action="store_true", default=False,
                            help="paired samples snv calling") 
    optionparser.add_option("--multi_samples", dest="multi_samples", action="store_true", default=False,
                            help="multi-sample snv calling")  

    

    (options, args) = optionparser.parse_args()    

    config = ExomePipelineConfig()
    config.from_xml(options.config_file)
    analysis = ExomeAnalysisConfig()
    analysis.from_xml(options.analysis_file, config.output_dir)

    
    if not (options.local ^ options.cluster):
        parser.error("Must set either --local or --cluster to run job")
    if options.local:
        jobrunfunc = run_local
    elif options.cluster:
        jobrunfunc = qsub
    
    # Reads Realignment
    fast_lane_level_processing(analysis, config, options.num_processors, jobrunfunc)
    
    # snps calls
    if options.multi_samples:
        sgatk.snps_calling_multipleSamples(analysis, config, options.num_processors, jobrunfunc)
        # Samtools Work in progress. 12-01-11
        sst.snps_calling_multipleSamples(analysis, config, options.num_processors, jobrunfunc)
    elif options.paired_samples:
        # gatk Work in progress. 12-01-11
        # sgatk.snps_calling_pairedSamples(analysis, config, options.num_processors, jobrunfunc)
        sst.snps_calling_pairedSamples(analysis, config, options.num_processors, jobrunfunc)

